import { defineStore } from 'pinia'
import { ref } from 'vue'
import { getCostumeList, getCostumeById } from '@/api/costumeApi'

export const useCostumeStore = defineStore('costume', () => {
    // 状态
    const costumeList = ref([])
    const currentCostume = ref(null)
    const loading = ref(false)
    const pagination = ref({
        pageNum: 1,
        pageSize: 10,
        total: 0
    })

    // actions
    const fetchCostumeList = async (pageNum = 1, pageSize = 10) => {
        loading.value = true
        try {
            const response = await getCostumeList(pageNum, pageSize)
            costumeList.value = response.records || []
            pagination.value = {
                pageNum: response.current,
                pageSize: response.size,
                total: response.total
            }
            return response
        } catch (error) {
            console.error('获取服装列表失败:', error)
            throw error
        } finally {
            loading.value = false
        }
    }

    const fetchCostumeById = async (id) => {
        if (!id || id < 1) {
            throw new Error('无效的服装ID')
        }

        loading.value = true
        try {
            const response = await getCostumeById(id)
            currentCostume.value = response
            return response
        } catch (error) {
            console.error('获取服装详情失败:', error)
            throw error
        } finally {
            loading.value = false
        }
    }

    const resetCurrentCostume = () => {
        currentCostume.value = null
    }

    return {
        // state
        costumeList,
        currentCostume,
        loading,
        pagination,

        // actions
        fetchCostumeList,
        fetchCostumeById,
        resetCurrentCostume
    }
})